import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

import routers from './routers.js';
import store from '@/store'


/**
 * 编程式路由多次点击会 thorws: Uncaught (in promise) NavigationDuplicated
 * 解决方式:
 *    重写路由的push|replace
 */
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

/**
 * call|apply区别
 *   相同点：都可调用函数一次，都可篡改函数的上下文一次。
 *   不同点：call与apply传递参数：call传递参数用逗号隔开，apply方法执行，传递数组。
 * @param {*} location 告诉原来的push方法，你往哪里跳转（传递哪些参数）
 * @param {*} resolve 成功回调。
 * @param {*} reject 失败回调。
 */
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject);
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}

let router = new VueRouter({
    routes: routers,
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})

/**
 * 前置守卫
 */
router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name;
    if (token) {
        if (to.path == "/login" || to.path == '/register') {
            next('/')
        } else {
            if (name) {
                next();
            } else {
                try {
                    await store.dispatch('getUserInfo');
                    next();
                } catch (error) {
                    await store.dispatch('logout');
                    next('/login');
                }
            }
        }
    } else {
        let toPath = to.path
        if (toPath.indexOf('/trade') != -1 || toPath.indexOf('/pay') != -1 || toPath.indexOf('/center') != -1) {
            next('/login?redirect=' + toPath);
        } else {
            next();
        }
    }
})

export default router;